package com.iogogogo.supervisord4j.api;

import com.iogogogo.supervisord.base.BaseResult;
import com.iogogogo.supervisord.base.ResponseWrapper;
import com.iogogogo.supervisord.properties.SupervisordProperties;
import com.iogogogo.supervisord4j.pojo.entity.InstanceEntity;
import com.iogogogo.supervisord4j.properties.InstanceProperties;
import com.iogogogo.supervisord4j.repository.InstanceRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.jooq.lambda.Seq;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created by tao.zeng on 2021/7/13.
 */
@Api(value = "supervisord4j", tags = "Instance Api")
@RestController
@RequestMapping("/api/instance")
public class InstanceApi implements BaseResult {

    private final InstanceProperties instanceProperties;

    private final InstanceRepository instanceRepository;

    public InstanceApi(InstanceProperties instanceProperties, InstanceRepository instanceRepository) {
        this.instanceProperties = instanceProperties;
        this.instanceRepository = instanceRepository;
    }

    @ApiOperation("获取Instance实例详情")
    @GetMapping
    public ResponseWrapper<?> instance() {
        List<InstanceEntity> list = instanceRepository.findAll();
        Map<String, SupervisordProperties> instance = instanceProperties.getInstance();
        Set<String> keySet = instance.keySet();

        List<InstanceEntity> collect = Seq.cast(keySet.stream(), String.class)
                .leftOuterJoin(list.stream(), (left, right) -> StringUtils.equals(left, right.getInstance()))
                .map(x -> {
                    InstanceEntity v2 = x.v2();
                    String v1 = x.v1;
                    SupervisordProperties properties = instance.getOrDefault(v1, new SupervisordProperties());
                    String url = properties.getUrl();
                    String newUrl = StringUtils.replace(url, "/RPC2", "");
                    if ((Objects.nonNull(v2))) {
                        v2.setServer(url);
                        return v2;
                    } else return new InstanceEntity(v1, v1, null, url, newUrl, newUrl);
                })
                .collect(Collectors.toList());

        return ok(collect);
    }

    @ApiOperation("保存详情关系")
    @RequestMapping(method = {RequestMethod.POST, RequestMethod.PUT})
    public ResponseWrapper<?> merge(@RequestBody InstanceEntity entity) {
        return ok(instanceRepository.save(entity));
    }
}
